//注册并使用弹框组件
import { createApp, h, ref } from "vue";
import Modal from '../components/Modal.vue';

export function createModal() {
    //全局实列存储
    const instances: any = [];


    //封装了弹框内容
    function modal(options: any = {}) {
        //创建div元素
        const container = document.createElement('div');
        document.body.appendChild(container);

        const visible = ref(true);

        const app = createApp({
            setup() {
                const onClose = () => {
                    visible.value = false;
                    setTimeout(() => {
                        app.unmount();
                        container.remove();
                        const index = instances.findIndex((instance: any) => instance === app)
                        if (index !== -1) {
                            instances.splice(index, 1)
                        }
                    }, 300); //给过渡动画留时间
                };

                return () => h(Modal, {
                    modelValue: visible.value,
                    'onUpdate:modelValue': (val: any) => {
                        visible.value = val;
                        if (!val) onClose();
                    },
                    onConfirm: () => {
                        if (options.onConfirm) options.onConfirm();
                        onClose();
                    },
                    onClancel: () => {
                        if (options.onClancel) options.onClancel();
                        onClose();
                    },
                    ...options
                }, options.slots || {})

            }
        });

        instances.push(app);
        app.mount(container);

        return {
            close: () => {
                visible.value = false;
            }
        }
    }


    //alert弹框
    modal.alert = (content: any, title: any = '提示', onConfirm: any) => {
        return modal({
            title,
            content,
            showCancel: false,
            onConfirm
        })
    };

    //confirm弹框
    modal.onfirm = (content: any, title: any = '确认', onConfirm: any, onClancel: any) => {
        return modal({
            title,
            content,
            onConfirm,
            onClancel
        })
    };

    //关闭所有的弹框
    modal.closeAll = () => {
        instances.forEach((instance: any) => {
            const vm = instance._instance.subTree.component.ctx;
            if (vm?.close) vm.close();
        })
    };

    return modal;

}

export default {
    install(app: any) {
        const modal = createModal();
        app.config.globalProperties.$modal = modal;
        app.provide('modal', modal)
    }
}